// 宠物领养
const Router = require("@koa/router");
const { shop, ObjectId } = require("../models/mongo");
var jwt = require("jsonwebtoken");

const router = new Router({
    prefix: "/api",
});

// 配置 multer
const path = require('path');
const { writeFile } = require("fs/promises");
const multer = require('@koa/multer');
const upload = multer();

// 自定义中间件
const { verifyToken } = require("../middleware/verity");

// 获取post的body
const { bodyParser } = require("@koa/bodyparser");

// 获取所有帖子
router.get("/allShop", async (ctx) => {
    const { page = 1, pageSize = 8 } = ctx.query;
    const total = await shop.countDocuments();

    const list = await shop
        .find()
        .skip((page - 1) * pageSize)
        .limit(pageSize * 1)
        .sort({ _id: -1 })
        .toArray();
    ctx.body = {
        code: 200,
        message: "success",
        total,
        page,
        pageSize,
        list,
    }
});



// 添加
// router.post("/addBlog", bodyParser(), async (ctx) => {
//     const { title, time, publishedAt, phone, au, article } = ctx.request.body;
//     const addBlogRes = await news.insertOne({ title, publishedAt, time, phone, au, article })

//     if (addBlogRes) {
//         ctx.body = {
//             code: 200,
//             message: "success",
//         };
//     }
// });


// 添加
router.post("/addshop", upload.single("avatar"), async (ctx) => {
    // console.log(ctx.request.body); // 查看其他表单字段
    // console.log(ctx.file); // 查看上传的文件
    const avatarName = ctx.file?.originalname || '';
    const { name, description, category, brand, price, availability, goods, phone, coos, site, time } = ctx.request.body;
    const addPetRes = await shop.insertOne({ name, description, category, brand, price, availability, goods, phone, site, coos, time, avatarName });
    if (avatarName != '') {
        await writeFile(path.resolve(__dirname, "../shopimage/", avatarName), ctx.file.buffer);
    }
    if (addPetRes) {
        ctx.body = {
            code: 200,
            message: "success",
        };
    }
});


// 修改
router.post("/updateShop", upload.single("avatar"), async (ctx) => {
    const avatarName = ctx.file?.originalname;
    // console.log(avatarName);
    const { id, name, description, category, brand, price, availability, goods, phone, site, coos } = ctx.request.body;
    let delPetRes
    if (avatarName) {
        delPetRes = await shop.updateOne({ _id: new ObjectId(id) }, {
            $set: { name, description, category, brand, price, availability, goods, phone, coos, site, avatarName },
        })
        await writeFile(path.resolve(__dirname, "../shopimage/", avatarName), ctx.file.buffer);
    } else {
        delPetRes = await shop.updateOne({ _id: new ObjectId(id) }, {
            $set: { name, description, category, brand, price, availability, goods, phone, coos, site },
        })
    }

    if (delPetRes) {
        ctx.body = {
            code: 200,
            message: "success",
        };
    }
});


// 删除
router.post("/delShop", bodyParser(), async (ctx) => {
    const { id } = ctx.request.body;
    const delPetRes = await shop.deleteOne({ _id: new ObjectId(id) })

    if (delPetRes) {
        ctx.body = {
            code: 200,
            message: "success",
        };
    }
});



// 查询商品接口
router.post("/selectShop", bodyParser(), async (ctx) => {
    const { filterQuery, page, pageSize = 8 } = ctx.request.body;

    // 根据过滤条件计算符合条件的总记录数
    const total = await shop.countDocuments(filterQuery);

    // 根据分页参数查询数据，skip用于跳过前面的数据，limit用于限制每页显示的数据条数
    const list = await shop
        .find(filterQuery)
        .skip((page - 1) * pageSize)
        .limit(pageSize)
        .sort({ _id: -1 }) // 排序，假设按创建时间倒序
        .toArray();

    // 返回给前端的响应数据
    ctx.body = {
        code: 200,
        message: "success",
        total,       // 确保返回的总数是过滤后的总数
        page,        // 当前页码
        pageSize,    // 每页数量
        list,        // 当前页的数据
    };
});




module.exports = router;